<template>
	<view class="tui-userinfo-box">
		<image-cropper :src="tempFilePath" @confirm="confirm" @cancel="cancel" :crop-fixed=true :crop-width="240" :crop-height="240"></image-cropper>
		<tui-list-cell padding="0" :arrow="true" @tap="toHeadPicEdit">
			<view class="tui-list-cell">
				<view>更换头像</view>
				<image lazy-load :src="cropFilePath" mode="aspectFit" class="tui-avatar"></image>
				<!-- <cropper ref="cropper" class="tui-avatar" @upload="myUpload" selWidth="660rpx" selHeight="660rpx" :avatarSrc="$cdn.appAvatar+headPic" avatarStyle="width:100rpx;height:100rpx;border-radius:6%;"> -->
				</cropper>
			</view>
		</tui-list-cell>
		<tui-list-cell padding="0"  >
			<view class="tui-list-cell" >
				<view>昵称</view>
				<view class="tui-content">
					<input v-model="userNameVal" confirm-type="保存" @blur="updateUserName" class="font-size-val"
					maxlength="50" type="text" />
				</view>
			</view>
		</tui-list-cell>
<!-- 		<tui-modal :show="showUserName" @cancel="hideUserNameModal" :custom="true" :fadein="true">
			<view class="tui-modal-custom">
				<view class="tui-prompt-title">昵称</view>
				<input placeholder="请输入新昵称" class="tui-input" v-model="newUserName" />
				<tui-button shape="circle" @click="updateUserName" size="small">立即提交</tui-button>
			</view>
		</tui-modal> -->
		<tui-list-cell padding="0" :arrow="true">
			<view class="tui-list-cell">
				<view>性别</view>
				<view class="tui-content">
					<picker @change="bindPickerSexChange" :value="sexIndex" :range="sexArray" range-key="name">
						<view >{{sexArray[sexIndex].name}}</view>
					</picker>
				</view>
			</view>
		</tui-list-cell>
		<tui-list-cell padding="0" :arrow="true">
			<view class="tui-list-cell">
				<view>出生日期</view>
				<view class="tui-content">
					<picker mode="date" :value="date" :start="startDate" :end="endDate" @change="bindDateChange">
						<view>{{date}}</view>
					</picker>
				</view>
			</view>
		</tui-list-cell>
		<tui-list-cell padding="0">
			<view class="tui-list-cell">
				<view>微信号</view>
				<view class="tui-content">
					<input v-model="wxNoVal" confirm-type="保存" @blur="updateWxNo" class="font-size-val"
					maxlength="50" type="text" />
				</view>
			</view>
		</tui-list-cell>
		<tui-list-cell padding="0" :arrow="true">
			<view class="tui-list-cell">
				<view>所在城市</view>
				<view class="tui-content">
					<picker :value="value" mode="multiSelector" @change="picker" 
					range-key="name" @columnchange="columnPicker" :range="multiArray">
						<view >{{provinceNameVal+' '+cityNameVal}}</view>
					</picker>
				</view>
			</view>
		</tui-list-cell>
		<tui-list-cell padding="0">
			<view class="tui-list-cell">
				<view>所在行业</view>
				<view class="tui-content">
					<input v-model="postJobVal" confirm-type="保存" @blur="updatePostJob" class="font-size-val"
					maxlength="50" type="text" />
				</view>
			</view>
		</tui-list-cell>
		<tui-list-cell padding="0" :arrow="true" >
			<view class="tui-list-cell" @tap="toPhotoEdit">
				<view>我的相册</view>
				<view class="tui-content">编辑</view>
			</view>
		</tui-list-cell>
		<tui-list-cell padding="0" :arrow="true" :last="true">
			<view class="tui-list-cell" @tap="toEditSignPage">
				<view class="tui-sign-title">个性签名</view>
				<view class="tui-sign">{{sign}}</view>
			</view>
		</tui-list-cell>
		<view class="tui-btn-box">
			<button class="btn-primary" hover-class="btn-hover" @tap="toMemberDetail" type="primary">预览个人信息</button>
			<!-- <button class="btn-primary btn-gray" hover-class="btn-gray-hover" formType="reset">重置</button> -->
		</view>
	</view>
</template>

<script>
import { mapState, mapMutations, mapActions } from 'vuex';
import tuiListCell from "@/components/list-cell/list-cell"
import ImageCropper from "@/components/invinbg-image-cropper/invinbg-image-cropper.vue";
import tuiModal from "@/components/modal/modal"
import tuiButton from "@/components/button/button"
var util = require('../../utils/util.js');
const QQMapWX = require('../../libs/qqmap-wx-jssdk.min.js');
const cityData = require('../../utils/picker.city.js')
const cityBeijData = require('../../utils/picker.city-beij.js')
export default {
	computed: mapState(['isLogin', 'token', 'headPic','userName','sign','sex','birthday','provinceName','provinceCode',
	'cityCode','cityName','wxNo','postJob','memberId']),
	components: {
		tuiListCell,
		ImageCropper,
		tuiModal,
		tuiButton
	},
	data() {
		return {
			$cdn:this.$cdn,
			qqmapsdk: null,
			tempFilePath: '',
			cropFilePath: '',
			sexArray: [{name:'未选择',id:0},{name: '男',id:1},{name: '女',id:2}],
			sexIndex:0,
			date: '',
			startDate:getDate('start'),
			endDate:getDate('end'),
			
			selectList: cityData, //接口返回picker数据,此处就直接使用本地测试数据
			selectListTwo: cityBeijData, //第一个默认加载北京
			multiArray: [], //picker数据
			value: [0, 0],
			provinceNameVal:'',
			provinceCodeVal:'',
			cityCodeVal:'',
			cityNameVal:'',
			wxNoVal:'',
			postJobVal:'',
			userNameVal:''
		}
	},
	onLoad() {
		this.provinceNameVal=this.provinceName;
		this.cityNameVal=this.cityName;
		this.postJobVal=this.postJob;
		this.userNameVal=this.userName;
		this.wxNoVal=this.wxNo;
		this.qqmapsdk = new QQMapWX({
			key: 'W4WBZ-TUD65-IDAIR-QPM36-HMFQ5-CGBZP'
		});
		
		// 默认初始化是北京
		this.multiArray = [
			this.toArr(this.selectList),
			this.toArr(this.selectListTwo)
		]
	},
	created() {
		this.cropFilePath=this.$cdn.appAvatar+this.headPic;
		this.sexIndex=this.sex;
		this.date=this.birthday;
	},

	methods: {
		...mapMutations(['setUserInfo']),
		toPhotoEdit(){
			uni.navigateTo({
				url:'photo-edit'
			})
		},
		toHeadPicEdit() {
		    uni.chooseImage({
		        count: 1, //默认9
		        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
		        sourceType: ['album'], //从相册选择
		        success: (res) => {
		            this.tempFilePath = res.tempFilePaths.shift()
		        }
		    });
		},
		toMemberDetail() {
			uni.navigateTo({
				url: '../member/member-detail?memberId=' + this.memberId + '&userName=' + this.userName
			});
		},
		confirm(e) {
		    this.tempFilePath = ''
		    // this.cropFilePath = e.detail.tempFilePath;
			this.uploadHeadPicToEnd(e.detail.tempFilePath);
		},
		cancel() {
		    console.log('canceled')
		},
		uploadHeadPicToEnd(filePath){
			this.tui
				.uploadFile('/auth/api/member/uploadHeadPic', filePath)
				.then(res => {
					console.log('uploadHeadPicToEnd上传结果' + JSON.stringify(res));
					if (res.code == 0) {
						console.log(JSON.stringify(res));
						this.cropFilePath=this.$cdn.appAvatar+res.data;
						// 设置state头像
						this.setUserInfo({headPic: res.data});
					}
				})
				.catch(res => {
					console.log(res);
				});
		},
		updateUserName(){
			let postData = { userName: this.userNameVal };
			this.updateMain(postData,"userName");
		},
		updateWxNo(){
			let postData = { wxNo: this.wxNoVal };
			this.updateMain(postData,"wxNo");
		},
		updatePostJob(){
			let postData = { postJob: this.postJobVal };
			this.updateMain(postData,"postJob");
		},
		updateMain(postData,opt){
			let that=this;
			// let postData = { photos: photosSrc };
			this.tui
				.request('/auth/api/member/update', postData, 'POST', false, true)
				.then(res => {
					if (res.code == 0) {
						// this.tui.toast('更新成功', 1000, true);
						if(opt==='userName'){
							this.setUserInfo({userName: postData.userName});
						}else if(opt==='sex'){
							this.setUserInfo({sex: postData.sex});
						}else if(opt==='birthday'){
							this.setUserInfo({birthday: postData.birthdayStr});
						}else if(opt==='wxNo'){
							this.setUserInfo({wxNo: postData.wxNo});
						}else if(opt==='postJob'){
							this.setUserInfo({postJob: postData.postJob});
						}else if(opt==='city'){
							this.setUserInfo(postData);
						}
					}else{
						this.tui.toast('更新失败', 1000, true);
					}
				})
				.catch(res => {
					console.log(res);
				});
		},
		bindPickerSexChange: function(e) {
			console.log('bindPickerSexChange发送选择改变，携带值为：' + e.target.value)
			this.sexIndex = e.target.value;
			let postData = { sex:  this.sexArray[this.sexIndex].id};
			this.updateMain(postData,"sex");
		},
		bindDateChange: function(e) {
			console.log('bindDateChange发送选择改变，携带值为：' + e.target.value)
			this.date = e.target.value;
			this.updateMain({ birthdayStr: this.date },"birthday");
		},
		toEditSignPage(){
			uni.navigateTo({
				url: 'sign-edit'
			});
		},
		// 所在城市选择确定
		picker: function(e) {
			console.log('picker');
			let value = e.detail.value;
			if (this.selectList.length > 0) {
				this.provinceNameVal = this.selectList[value[0]].name;
				this.cityNameVal = this.selectListTwo[value[1]].name;
				this.provinceCodeVal = this.selectList[value[0]].id;
				this.cityCodeVal = this.selectListTwo[value[1]].id;
				this.updateMain({ provinceName: this.provinceNameVal,provinceCode: this.provinceCodeVal,
				cityName: this.cityNameVal,cityCode: this.cityCodeVal },"city");
			}
		},
		toArr(object) {
			let arr = [];
			for (let i in object) {
				let obj={id:object[i].id,name:object[i].fullname};
				arr.push(obj);
				// arr.push(object[i].id);
			}
			return arr;
		},
		columnPicker: function(e) {
			let that=this;
			//第几列 下标从0开始
			let column = e.detail.column;
			//第几行 下标从0开始
			let value = e.detail.value;
			console.log('columnPicker-column='+column);
			console.log('columnPicker-value='+value);
			let dataId=that.selectList[value].id;
			if (column === 0) {
				// 通过
				that.qqmapsdk.getDistrictByCityId({
					// 传入对应省份ID获得城市数据，传入城市ID获得区县数据,依次类推
					id: dataId, //对应接口getCityList返回数据的Id，如：北京是'110000'
					success: function(res) {
						//成功后的回调
						// console.log(res);
						// console.log('对应城市ID下的区县数据(以北京为例)：', JSON.stringify(res.result[0]));
						that.selectListTwo=res.result[0];
						that.multiArray = [
							that.multiArray[0],
							that.toArr(that.selectListTwo)
							// this.toArr(this.selectList[value].children[0].children)
						];
						that.value = [value, 0]
					},
					fail: function(error) {
						console.error(error);
					},
					complete: function(res) {
						console.log(res);
					}
				});
			}
		}
	}
}

	function getDate(type) {
		const date = new Date();
	
		let year = date.getFullYear();
		let month = date.getMonth() + 1;
		let day = date.getDate();
	
		if (type === 'start') {
			year = year - 60;
		} else if (type === 'end') {
			year = year + 2;
		}
		month = month > 9 ? month : '0' + month;;
		day = day > 9 ? day : '0' + day;
	
		return `${year}-${month}-${day}`;
	}
</script>

<style>
.tui-userinfo-box {
	padding-bottom: 20rpx;
	color: #333;
}

.tui-list-cell {
	width: 100%;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 24rpx 60rpx 24rpx 30rpx;
	font-size: 30rpx;
}

.tui-pr30 {
	padding-right: 30rpx;
}

.tui-avatar {
	width: 100rpx;
	height: 100rpx;
	display: block;
	border-radius: 6%;
}

.tui-content {
	width: 80%;
	font-size: 26rpx;
	color: #666;
	text-align: right;
}

/* modal 样式 */
	.tui-modal-custom {
		text-align: center
	}

	.tui-prompt-title {
		padding-bottom: 20rpx;
		font-size: 34rpx;
	}

	.tui-input {
		margin: 30rpx 40rpx;
		border-bottom: 1rpx solid #E6E6E6;
		padding-bottom: 20rpx;
		font-size: 32rpx;
	}
	/* modal 样式 end */
	.tui-sign-title{
		/* width: 20%; */
	}
	.tui-sign{
		font-size: 26rpx;
		color: #666;
		 /* flex-direction: row; */
		width: 80%;
		height: 200rpx;
		display: flex;
		align-items: center;
		/* text-align: right;
		vertical-position: ; */
		/* justify-content: right; */
		text-align: right;
	}
	.tui-btn-box {
		padding: 40rpx 50rpx;
		box-sizing: border-box;
	}
	.font-size-val{
		font-size: 30rpx;
	}
</style>
